<template>
  <el-container class="reader-container">
    <!-- 顶部工具栏 -->
    <el-header class="reader-header">
      <div class="header-left">
        <el-button @click="goBack" icon="ArrowLeft" text>返回</el-button>
        <el-divider direction="vertical" />
        <span class="book-title">{{ currentBook.title }}</span>
      </div>
      
      <div class="header-center">
        <el-button-group>
          <el-button @click="decreaseFontSize" icon="Minus" text />
          <el-button @click="resetFontSize" text>{{ fontSize }}px</el-button>
          <el-button @click="increaseFontSize" icon="Plus" text />
        </el-button-group>
        
        <el-divider direction="vertical" />
        
        <el-button-group>
          <el-button @click="toggleTheme" :icon="themeIcon" text />
          <el-button @click="toggleFullscreen" :icon="fullscreenIcon" text />
        </el-button-group>
      </div>
      
      <div class="header-right">
        <el-button @click="showBookmarks = true" icon="Star" text>
          书签 ({{ bookmarks.length }})
        </el-button>
        <el-button @click="showOutline = true" icon="Menu" text>目录</el-button>
      </div>
    </el-header>

    <!-- 主要内容区域 -->
    <el-main class="reader-main">
      <div class="reader-content" :class="themeClass" :style="{ fontSize: fontSize + 'px' }">
        <div class="chapter-content" v-html="currentChapter.content"></div>
      </div>
      
      <!-- 翻页按钮 -->
      <div class="page-navigation">
        <el-button 
          @click="previousPage" 
          :disabled="currentPage <= 1"
          type="primary" 
          circle
          icon="ArrowLeft"
        />
        <span class="page-info">{{ currentPage }} / {{ totalPages }}</span>
        <el-button 
          @click="nextPage" 
          :disabled="currentPage >= totalPages"
          type="primary" 
          circle
          icon="ArrowRight"
        />
      </div>
    </el-main>

    <!-- 目录侧边栏 -->
    <el-drawer 
      v-model="showOutline" 
      title="目录" 
      direction="rtl" 
      size="300px"
    >
      <el-tree
        :data="outline"
        :props="outlineProps"
        @node-click="handleOutlineClick"
        default-expand-all
        highlight-current
        :current-node-key="currentChapter.id"
      >
        <template #default="{ node, data }">
          <span class="outline-node">
            <el-icon v-if="data.type === 'chapter'"><Document /></el-icon>
            <el-icon v-else><Folder /></el-icon>
            {{ node.label }}
          </span>
        </template>
      </el-tree>
    </el-drawer>

    <!-- 书签侧边栏 -->
    <el-drawer 
      v-model="showBookmarks" 
      title="书签" 
      direction="rtl" 
      size="300px"
    >
      <div class="bookmarks-container">
        <div class="bookmarks-header">
          <el-button type="primary" @click="addBookmark" size="small">
            <el-icon><Plus /></el-icon>
            添加书签
          </el-button>
        </div>
        
        <el-empty v-if="bookmarks.length === 0" description="暂无书签" />
        
        <div v-else class="bookmarks-list">
          <el-card 
            v-for="bookmark in bookmarks" 
            :key="bookmark.id"
            class="bookmark-item"
            shadow="hover"
          >
            <div class="bookmark-content">
              <div class="bookmark-title">{{ bookmark.title }}</div>
              <div class="bookmark-page">第 {{ bookmark.page }} 页</div>
              <div class="bookmark-time">{{ bookmark.time }}</div>
            </div>
            <div class="bookmark-actions">
              <el-button 
                @click="goToBookmark(bookmark)" 
                type="primary" 
                size="small"
                text
              >
                跳转
              </el-button>
              <el-button 
                @click="removeBookmark(bookmark.id)" 
                type="danger" 
                size="small"
                text
              >
                删除
              </el-button>
            </div>
          </el-card>
        </div>
      </div>
    </el-drawer>

    <!-- 添加书签对话框 -->
    <el-dialog 
      v-model="addBookmarkDialog" 
      title="添加书签" 
      width="400px"
    >
      <el-form :model="newBookmark" label-width="80px">
        <el-form-item label="标题">
          <el-input v-model="newBookmark.title" placeholder="请输入书签标题" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input 
            v-model="newBookmark.note" 
            type="textarea" 
            placeholder="请输入备注信息（可选）"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addBookmarkDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmAddBookmark">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 阅读进度条 -->
    <div class="progress-bar">
      <el-progress 
        :percentage="readingProgress" 
        :show-text="false"
        :stroke-width="4"
        color="#409eff"
      />
    </div>
  </el-container>
</template>

<script>
import { 
  ArrowLeft, 
  ArrowRight, 
  Minus, 
  Plus, 
  Star, 
  Menu, 
  Document, 
  Folder,
  Moon,
  Sunny,
  FullScreen,
  Close
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'ReaderPage',
  components: {
    ArrowLeft,
    ArrowRight,
    Minus,
    Plus,
    Star,
    Menu,
    Document,
    Folder,
    Moon,
    Sunny,
    FullScreen,
    Close
  },
  data() {
    return {
      // 当前书籍信息
      currentBook: {
        title: '三体',
        author: '刘慈欣',
        totalPages: 500
      },
      
      // 阅读设置
      fontSize: 16,
      theme: 'light', // light, dark, sepia
      isFullscreen: false,
      
      // 阅读进度
      currentPage: 1,
      totalPages: 500,
      
      // 侧边栏控制
      showOutline: false,
      showBookmarks: false,
      
      // 书签相关
      addBookmarkDialog: false,
      newBookmark: {
        title: '',
        note: ''
      },
      bookmarks: [
        {
          id: 1,
          title: '第一章开始',
          page: 1,
          time: '2024-01-15 10:30',
          note: '开始阅读'
        },
        {
          id: 2,
          title: '重要情节',
          page: 45,
          time: '2024-01-15 14:20',
          note: '叶文洁的重要发现'
        }
      ],
      
      // 目录结构
      outline: [
        {
          id: 1,
          label: '第一部：地球往事',
          type: 'part',
          children: [
            {
              id: 11,
              label: '第一章：科学边界',
              type: 'chapter',
              page: 1
            },
            {
              id: 12,
              label: '第二章：农场主',
              type: 'chapter',
              page: 25
            },
            {
              id: 13,
              label: '第三章：红岸基地',
              type: 'chapter',
              page: 50
            }
          ]
        },
        {
          id: 2,
          label: '第二部：黑暗森林',
          type: 'part',
          children: [
            {
              id: 21,
              label: '第一章：面壁者',
              type: 'chapter',
              page: 100
            },
            {
              id: 22,
              label: '第二章：破壁人',
              type: 'chapter',
              page: 150
            }
          ]
        }
      ],
      outlineProps: {
        children: 'children',
        label: 'label'
      },
      
      // 当前章节
      currentChapter: {
        id: 11,
        title: '第一章：科学边界',
        content: `
          <p>叶文洁站在红岸基地的观测台上，望着远方的群山。这里是地球文明的边缘，也是她寻找外星文明的起点。</p>
          
          <p>二十年前，她的父亲叶哲泰在文革中被迫害致死，母亲也在绝望中自杀。从那时起，叶文洁就对人类文明产生了深深的怀疑。</p>
          
          <p>现在，她终于有机会向宇宙发出信号，寻找可能存在的外星文明。也许，只有来自宇宙的干预，才能拯救这个疯狂的世界。</p>
          
          <p>她深吸一口气，按下了发送按钮。一道强大的电磁波射向宇宙深处，带着地球文明的信息，也带着她的希望和绝望。</p>
          
          <p>叶文洁不知道的是，这个信号将在四百年后到达三体星系，引发一场改变人类命运的巨大危机。</p>
          
          <p>而在更遥远的未来，这个信号还将成为人类文明与三体文明之间复杂关系的起点。</p>
        `
      }
    }
  },
  computed: {
    // 阅读进度百分比
    readingProgress() {
      return Math.round((this.currentPage / this.totalPages) * 100)
    },
    
    // 主题样式类
    themeClass() {
      return `theme-${this.theme}`
    },
    
    // 主题图标
    themeIcon() {
      return this.theme === 'dark' ? 'Sunny' : 'Moon'
    },
    
    // 全屏图标
    fullscreenIcon() {
      return this.isFullscreen ? 'Close' : 'FullScreen'
    }
  },
  methods: {
    // 返回上一页
    goBack() {
      // 如果有 bookId 参数，返回到图书详情页，否则返回上一页
      if (this.$route.params.bookId) {
        this.$router.push({
          name: 'BookDetailPage',
          params: { bookId: this.$route.params.bookId }
        })
      } else {
        this.$router.go(-1)
      }
    },
    
    // 字体大小控制
    decreaseFontSize() {
      if (this.fontSize > 12) {
        this.fontSize -= 2
      }
    },
    
    increaseFontSize() {
      if (this.fontSize < 24) {
        this.fontSize += 2
      }
    },
    
    resetFontSize() {
      this.fontSize = 16
    },
    
    // 主题切换
    toggleTheme() {
      const themes = ['light', 'dark', 'sepia']
      const currentIndex = themes.indexOf(this.theme)
      const nextIndex = (currentIndex + 1) % themes.length
      this.theme = themes[nextIndex]
      ElMessage.success(`已切换到${this.theme === 'light' ? '浅色' : this.theme === 'dark' ? '深色' : '护眼'}主题`)
    },
    
    // 全屏切换
    toggleFullscreen() {
      this.isFullscreen = !this.isFullscreen
      if (this.isFullscreen) {
        document.documentElement.requestFullscreen()
      } else {
        document.exitFullscreen()
      }
    },
    
    // 翻页
    previousPage() {
      if (this.currentPage > 1) {
        this.currentPage--
        this.updateChapter()
      }
    },
    
    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++
        this.updateChapter()
      }
    },
    
    // 更新章节内容
    updateChapter() {
      // 这里可以根据页码加载对应的章节内容
      ElMessage.info(`已跳转到第 ${this.currentPage} 页`)
    },
    
    // 目录点击处理
    handleOutlineClick(data) {
      if (data.type === 'chapter') {
        this.currentPage = data.page
        this.currentChapter.id = data.id
        this.currentChapter.title = data.label
        this.showOutline = false
        ElMessage.success(`已跳转到 ${data.label}`)
      }
    },
    
    // 书签相关
    addBookmark() {
      this.newBookmark.title = `第 ${this.currentPage} 页`
      this.addBookmarkDialog = true
    },
    
    confirmAddBookmark() {
      if (!this.newBookmark.title.trim()) {
        ElMessage.warning('请输入书签标题')
        return
      }
      
      const bookmark = {
        id: Date.now(),
        title: this.newBookmark.title,
        page: this.currentPage,
        time: new Date().toLocaleString(),
        note: this.newBookmark.note
      }
      
      this.bookmarks.push(bookmark)
      this.addBookmarkDialog = false
      this.newBookmark = { title: '', note: '' }
      ElMessage.success('书签添加成功')
    },
    
    goToBookmark(bookmark) {
      this.currentPage = bookmark.page
      this.showBookmarks = false
      ElMessage.success(`已跳转到书签：${bookmark.title}`)
    },
    
    removeBookmark(bookmarkId) {
      ElMessageBox.confirm('确定要删除这个书签吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.bookmarks = this.bookmarks.filter(b => b.id !== bookmarkId)
        ElMessage.success('书签已删除')
      })
    }
  },
  
  // 键盘快捷键
  mounted() {
    document.addEventListener('keydown', this.handleKeydown)
  },
  
  beforeUnmount() {
    document.removeEventListener('keydown', this.handleKeydown)
  },
  
  methods: {
    handleKeydown(event) {
      switch (event.key) {
        case 'ArrowLeft':
          this.previousPage()
          break
        case 'ArrowRight':
          this.nextPage()
          break
        case '=':
        case '+':
          this.increaseFontSize()
          break
        case '-':
          this.decreaseFontSize()
          break
        case '0':
          this.resetFontSize()
          break
        case 'b':
          this.addBookmark()
          break
        case 'm':
          this.showOutline = !this.showOutline
          break
      }
    }
  }
}
</script>

<style scoped>
.reader-container {
  height: 100vh;
  background-color: #f5f7fa;
}

.reader-header {
  background: white;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  height: 60px;
}

.header-left,
.header-center,
.header-right {
  display: flex;
  align-items: center;
  gap: 10px;
}

.book-title {
  font-weight: 600;
  color: #303133;
}

.reader-main {
  padding: 0;
  position: relative;
  background: white;
}

.reader-content {
  max-width: 800px;
  margin: 0 auto;
  padding: 40px 20px;
  line-height: 1.8;
  min-height: calc(100vh - 120px);
}

.chapter-content {
  text-align: justify;
}

.chapter-content p {
  margin-bottom: 1.5em;
  text-indent: 2em;
}

/* 主题样式 */
.theme-light {
  background-color: #ffffff;
  color: #303133;
}

.theme-dark {
  background-color: #1a1a1a;
  color: #e4e7ed;
}

.theme-sepia {
  background-color: #f4ecd8;
  color: #5c4b37;
}

.page-navigation {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  align-items: center;
  gap: 20px;
  background: rgba(255, 255, 255, 0.9);
  padding: 10px 20px;
  border-radius: 25px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.page-info {
  font-weight: 600;
  color: #606266;
}

.outline-node {
  display: flex;
  align-items: center;
  gap: 8px;
}

.bookmarks-container {
  padding: 20px;
}

.bookmarks-header {
  margin-bottom: 20px;
  text-align: center;
}

.bookmarks-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.bookmark-item {
  border-radius: 8px;
}

.bookmark-content {
  margin-bottom: 10px;
}

.bookmark-title {
  font-weight: 600;
  margin-bottom: 5px;
}

.bookmark-page {
  color: #409eff;
  font-size: 12px;
  margin-bottom: 5px;
}

.bookmark-time {
  color: #909399;
  font-size: 12px;
}

.bookmark-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.progress-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .reader-header {
    flex-direction: column;
    height: auto;
    padding: 10px;
    gap: 10px;
  }
  
  .header-center {
    order: 3;
  }
  
  .reader-content {
    padding: 20px 15px;
  }
  
  .page-navigation {
    bottom: 10px;
    padding: 8px 15px;
  }
}
</style>